package com.lzy.conf;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lzy.common.CommonEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Slf4j
public class BaseEntityMetaObjectHandler implements MetaObjectHandler {

    /**
     * 创建时间
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.getOriginalObject() instanceof CommonEntity) {
            CommonEntity entity = (CommonEntity) metaObject.getOriginalObject();
            if (entity.getCreateTime() == null) {
                this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
            }
            if (entity.getUpdateTime() == null) {
                this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            }
            if (entity.getVersion() == null) {
                this.strictInsertFill(metaObject, "version", Integer.class, 1);
            }
            if (entity.getDelFlag() == null) {
                this.strictInsertFill(metaObject, "delFlag", Boolean.class, false);
            }
        }
    }

    /**
     * 更新时间
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.getOriginalObject() instanceof CommonEntity) {
            CommonEntity entity = (CommonEntity) metaObject.getOriginalObject();
            if (entity.getUpdateTime() == null) {
                this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            }
        }
    }
}
